<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Category as CategoryModel;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 分类管理
 *
 * @icon   fa fa-list
 * @remark 用于管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Category extends Backend
{

    /**
     * @var \app\common\model\Category
     */
    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\common\model\Category');

        $this->categorylist = $this->model
            ->order('sort desc,id desc')
            ->select();
        // 获取分类列表
        $typeList = CategoryModel::getTypeList();


        $this->view->assign("typeList", $typeList);
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->assignconfig('typeList', $typeList);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            // $search = $this->request->request("search");
            // $type = $this->request->request("type");

            //构造父类select列表选项数据
            // $list = [];
            // foreach ($this->categorylist as $k => $v) {
            //     if ($search) {
            //         $searchIndex = stripos($v['name'], $search);
            //         if ($v['type'] == $type && $searchIndex !== false) {
            //             $list[] = $v;
            //         } elseif ($type == "all" || empty($type) && $searchIndex !== false) {
            //             $list[] =  $v;
            //         }
            //     } else {
            //         if ($type == "all" || $type == null) {
            //             $list = $this->categorylist;
            //         } elseif ($v['type'] == $type) {
            //             $list[] = $v;
            //         }
            //     }
            // }

            // $total = count($list);
            // $result = array("total" => $total, "rows" => $list);

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // print_r($where);
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            // print_r($list);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $data = [
            'name' => $params['name'],
            'sort' => $params['sort'],
            'type' => $params['type'],
        ];

        $validate = validate('Category');
        if (!$validate->scene('add')->check($data)) {
            $this->error($validate->getError());
        }

        $category = $this->model->where('name', $params['name'])->find();
        if ($category) {
            $this->error('分类名称已存在');
        }

        $adminId = $this->auth->__get('id');
        $params['create_user'] = $adminId;
        $params['update_user'] = $adminId;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $data = [
                    'name' => $params['name'],
                    'sort' => $params['sort'],
                    'type' => $params['type'],
                ];
                // 数据合法性校验
                $validate = validate('Category');
                if (!$validate->scene('edit')->check($data)) {
                    $this->error($validate->getError());
                }

                $category = $this->model
                    ->where('id', '<>', $ids)
                    ->where('name', $params['name'])
                    ->find();

                if ($category) {
                    $this->error('分类名称已存在');
                }

                $adminId = $this->auth->__get('id');
                $params['update_user'] = $adminId;

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                if ($item->adminDishes) {
                    throw new Exception("分类下有产品不可删除");
                }
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    public function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        // 搜索键
        $searchKey = $this->request->request("searchKey");
        // 搜索值
        $searchValue = $this->request->request("searchValue");
        //主键
        $primarykey = $this->request->request("keyField");
        //自定义参数
        $custom = $this->request->request("custom/a");
        // dump($orderby);
        $order = $orderby[0][0] . " " . $orderby[0][1];
        $list = $this->model->page($page, $pagesize)->order($order)->field($primarykey . ',' . $field)->select();
        if ($custom) {
            if (isset($custom['type'])) {
                // 获取类型为套餐的数据
                if ($custom['type'] == 'setmeal') {
                    $list = $this->model->where('type', 2)->page($page, $pagesize)->order($order)->field($primarykey . ',' . $field)->select();
                }
            }
        }
        // dump($list);

        $total = count($list);
        if ($searchValue) {
            $index = 0;
            for ($i = 0; $i < $total; $i++) {
                if ($list[$i][$searchKey] == $searchValue) {
                    $index = $i;
                    break;
                }
            }

            if ($index !== 0) {
                $tmp = $list[0];
                $list[0] = $list[$index];
                $list[$index] = $tmp;
            }
        }

        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }
}
